<template>
  <view class="activity-detail">
    <!-- 主要内容区域 -->
    <!-- scroll-view 组件用于创建一个可滚动的视图区域 -->
    <!-- class="content" 为该滚动视图应用名为 content 的样式类 -->
    <!-- scroll-y 属性表示该视图区域仅允许在垂直方向上滚动 -->
    <scroll-view class="content" scroll-y>
      <!-- 活动标题 -->
      <view class="title-section">
        <text class="activity-title">{{ activityData.activityName || "活动标题" }}</text>
        <!-- 活动状态徽章组件，用于展示活动的当前状态 -->
        <!-- class="status-badge" 为基础样式类，定义徽章的通用样式 -->
        <!-- :class="activityData.status" 动态绑定活动状态对应的样式类，根据活动状态显示不同的视觉效果 -->
        <!-- 注释中的 {{ getStatusText(activityData.status) }} 原计划用于显示活动状态的文本，当前被注释暂不使用 -->
        <view class="status-badge" :class="activityData.status">
          <!--   {{ getStatusText(activityData.status) }} -->
        </view>
      </view>

      <!-- 基本信息卡片 -->
      <view class="info-card">
        <view class="info-item">
          <text class="label">📅报名时间</text>
          <text class="value"
            >{{ activityData.registrationStart || "待定" }} 至
            {{ activityData.registrationEnd || "待定" }}</text
          >
        </view>
        <view class="info-item">
          <text class="label">📅活动时间</text>
          <text class="value"
            >{{ activityData.activityStart || "待定" }} 至
            {{ activityData.activityEnd || "待定" }}</text
          >
        </view>
        <view class="info-item">
          <text class="label">📍 活动地点</text>
          <text class="value2">{{ activityData.activityLocation || "待定" }}</text>
        </view>
        <view class="info-item">
          <text class="label">👥 参与人数</text>
          <text class="value2"
            >{{ number || 0 }}/{{
              activityData.participantLimit || "不限"
            }}</text
          >
        </view>
        <view class="info-item">
          <text class="label">👤 负责人</text>
          <text class="value2">{{ activityData.responsiblePerson || "管理员" }}</text>
        </view>
        <view class="info-item">
          <text class="label">🏆 学分类型</text>
          <text class="value2">{{ activityData.creditType || "无" }}</text>
        </view>
        <view class="info-item">
          <text class="label">⭐ 学分分值</text>
          <text class="value2">{{ activityData.creditValue || 0 }}分</text>
        </view>
        <view class="info-item">
          <text class="label">📊 活动等级</text>
          <text class="value2">{{ activityData.activityLevel || "普通" }}</text>
        </view>
      </view>

      <!-- 活动描述 -->
      <view class="description-section">
        <text class="section-title">活动介绍</text>
        <view class="description-content">
          <text>{{ activityData.activityDes || "暂无活动介绍" }}</text>
        </view>
      </view>

      <!-- 活动要求 -->
      <view class="requirements-section" v-if="activityData.requirements">
        <text class="section-title">参与要求</text>
        <view class="requirements-content">
          <text>{{ activityData.requirements }}</text>
        </view>
      </view>

      <!-- 联系方式 -->
      <view class="contact-section" v-if="activityData.responsibleContact">
        <text class="section-title">联系方式</text>
        <view class="contact-content">
          <text>负责人：{{ activityData.responsiblePerson }}</text>
          <text>联系方式：{{ activityData.responsibleContact }}</text>
          <text v-if="activityData.supervisor">导师：{{ activityData.supervisor }}</text>
        </view>
      </view>

      <!-- 底部占位 -->
      <!-- 底部占位元素，用于为固定在底部的操作栏预留空间，避免内容被操作栏遮挡 -->
      <view class="bottom-placeholder"></view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="action-buttons">
        <!-- 主操作按钮，用于报名活动 -->
        <!-- class="primary-btn" 为按钮应用基础样式 -->
        <!-- :class="{ disabled: !canJoin }" 动态绑定 disabled 类，当 canJoin 为 false 时添加该类 -->
        <!-- @tap="handleJoin" 绑定点击事件，点击时触发 handleJoin 方法 -->
        <!-- :disabled="!canJoin" 动态设置按钮的禁用状态，当 canJoin 为 false 时禁用按钮 -->
        <!-- v-if="studentStatus !== '已录取'" 条件渲染，只有学生状态不为 '已录取' 时才显示该按钮 -->
        <!-- {{ getActionText() }} 动态显示按钮文本，文本内容由 getActionText 方法返回 -->
        <button class="primary-btn disabled" v-if="number === activityData.participantLimit && studentStatus === '未录取'">
          人数已满
        </button>
        <button
          class="primary-btn"
          :class="{ disabled: !canJoin }"
          @tap="handleJoin"
          :disabled="!canJoin"
          v-if="studentStatus === '未报名'||(studentStatus === '未录取'&&number<activityData.participantLimit)"
        >
          立即报名
        </button>
        <button class="cancel-btn" @tap="handleCancel" v-if="studentStatus === '已录取'">
          取消报名
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import {getActivityDetail} from "@/api/wlxz/act_detail.js";
import{joinActivity,deleteActivity} from "@/api/wlxz/act_behave.js";
import useUserStore from "@/store/modules/user";
import { useActivityDetailStore } from "@/store/modules/activity/activitydetail.js";
const userStore = useUserStore();
const activityDetailStore = useActivityDetailStore();

//活动详细数据
const activityData = ref({});
// 报名人数
const number = ref(0);
//获取活动详细信息,界面加载时候执行
const loadActivityDetail = async (id) => {
  uni.showLoading({ title: "加载中..." });
  const response = await getActivityDetail(id);
  console.log(response.data)
  activityData.value = response.data;
  //获取活动参加总人数
  const num = await activityDetailStore.loadActivityDetailList({
    activityId: activityData.value.activityId,
    status:"已录取"
  })
  number.value = num.total;
  //获取学生参与状态,每次加载界面都要获取一次学生状态
  getStudentStatus();
  //刷新界面
  uni.hideLoading();
};

// 学生参与状态
/**
 * 学生参与状态
 * 未报名 渲染立即报名按钮,执行报名方法,默认未报名
 * 已报名 渲染取消报名按钮,执行取消方法
 * 未录取 渲染人数已满标志,不允许进行操作
 */
const studentStatus = ref("未报名");
// 学生记录ID
const studentRecordId = ref(null);
//学生报名信息
const studentInfo = ref(null);

// 是否可以报名
const canJoin = computed(() => {
  const now = new Date().getTime();
  const regStart = new Date(activityData.value.registrationStart).getTime();
  const regEnd = new Date(activityData.value.registrationEnd).getTime();
  console.log(regEnd);
  return (
    activityData.value.status === "报名中" &&
    now >= regStart &&
    now <= regEnd &&
    studentStatus.value !== "已录取"
  );
});
// 获取学生参与状态,界面加载
const getStudentStatus = async () => {
  const params = {
    studentNumber: userStore.name,
    activityId: activityData.value.activityId,
  };
  const res = await activityDetailStore.loadActivityDetailList(params);
  if (res.total > 0) {
    studentInfo.value = res.data[0];  
    studentStatus.value = res.data[0].status;
    studentRecordId.value = res.data[0].id;
  }
};
// 处理报名
const handleJoin = () => {
  if (!canJoin.value) return;
  uni.showModal({
    title: "确认报名",
    content: `确定要报名参加"${activityData.value.activityName}"吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: "报名中..." });
          const data = {
            activityId: activityData.value.activityId,
            participantLimit: activityData.value.participantLimit,
            name: userStore.nickName,
            snumber: userStore.name,
          };
          const response = await joinActivity(data);
          if (response && response.code === 200) {
            uni.showToast({
              title: "报名成功",
              icon: "success",
            });
            // 重新加载活动详情以更新参与人数
            await loadActivityDetail(activityData.value.activityId);

            // 自动刷新页面 - 滚动到顶部
            uni.pageScrollTo({
              scrollTop: 0,
              duration: 300,
            });
          } else {
            uni.showToast({
              title: response?.msg || "报名失败",
              icon: "error",
            });
          }
        } catch (error) {
          console.error("报名失败:", error);
          uni.showToast({
            title: "网络错误，请重试",
            icon: "error",
          });
        } finally {
          uni.hideLoading();
        }
      }
    },
  });
};

// 处理取消报名
const handleCancel = () => {
  uni.showModal({
    title: "确认取消报名",
    content: `确定要取消报名“${activityData.value.activityName}”吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: "取消中..." });
          const response = await deleteActivity(studentRecordId.value);

          if (response && response.code === 200) {
            uni.showToast({
              title: "取消成功",
              icon: "success",
            });

            // 重新加载活动详情以更新参与人数
            loadActivityDetail(activityData.value.activityId);

            // 未学生报名状态赋值
            studentStatus.value = "未报名";
            // 自动刷新页面
            uni.pageScrollTo({
              scrollTop: 0,
              duration: 300,
            });
          } else {
            uni.showToast({
              title: response?.msg || "取消失败",
              icon: "error",
            });
          }
        } catch (error) {
          console.error("取消报名失败:", error);
          uni.showToast({
            title: "网络错误，请重试",
            icon: "error",
          });
        } finally {
          uni.hideLoading();
        }
      }
    },
  });
};

// 页面加载时获取数据
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const { id } = currentPage.options || {};
  if (id) {
    loadActivityDetail(id);
  } else {
    uni.showToast({
      title: "参数错误",
      icon: "error",
    });
  }
});
</script>

<style lang="scss" scoped>
.activity-detail {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8f9ff 0%, #f5f7fa 100%);
  position: relative;
}

.status-bar-placeholder {
  height: var(--status-bar-height);
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: relative;

  .back-btn {
    font-size: 40rpx;
    color: #333;
    margin-right: 20rpx;
  }

  .header-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
  }
}

.content {
  flex: 1;
  padding: 30rpx;
  padding-bottom: 120rpx;
}

.title-section {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

  .activity-title {
    font-size: 40rpx;
    font-weight: 700;
    color: #333;
    line-height: 1.4;
    margin-bottom: 20rpx;
  }

  .status-badge {
    display: inline-block;
    padding: 8rpx 20rpx;
    border-radius: 25rpx;
    font-size: 24rpx;
    font-weight: 500;

    &.upcoming {
      background: linear-gradient(135deg, #ff6b6b, #ff8e53);
      color: #fff;
    }

    &.ongoing {
      background: linear-gradient(135deg, #4ecdc4, #44a08d);
      color: #fff;
    }

    &.past {
      background: linear-gradient(135deg, #a8a8a8, #8e8e8e);
      color: #fff;
    }
  }
}

.info-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }

    .label {
      font-size: 28rpx;
      color: #666;
      flex: 1;
    }

    .value {
      font-size: 23rpx;
      color: #333;
      font-weight: 500;
      text-align: right;
      flex: 2;
    }
    .value2 {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
      text-align: right;
      flex: 2;
    }
  }
}

.description-section,
.requirements-section,
.contact-section {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

  .section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 20rpx;
  }

  .description-content,
  .requirements-content,
  .contact-content {
    font-size: 28rpx;
    color: #666;
    line-height: 1.6;
  }
}

.bottom-placeholder {
  height: 100rpx;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);

  .action-buttons {
    .primary-btn,
    .cancel-btn {
      width: 100%;
      height: 80rpx;
      border: none;
      border-radius: 40rpx;
      font-size: 32rpx;
      font-weight: 600;
      transition: all 0.3s ease;

      &:active {
        transform: translateY(2rpx);
      }
    }

    .primary-btn {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #fff;

      &.disabled {
        background: #ccc;
        opacity: 0.7;
      }
    }

    .cancel-btn {
      background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
      color: #fff;
    }
  }
}
</style>
